const userModel=require('../../models/element-admin/user')
const fs = require('fs')
const path = require('path')
const cateModel = require('../../models/webapp/cate')
const titleModel = require('../../models/article/title')
class TitleController{
static async getImage(ctx){
  // 将其放到后端某地
  // 获取图片ctx.request.files是固定的,file是前端upload插件传递过来的文件名
  const file = ctx.request.files.file
  const readStream = fs.createReadStream(file.path)
  const filePath = `/cdn/${Date.now()}_${file.name}`
  const writeStream = fs.createWriteStream(path.resolve(__dirname, `../../public${filePath}`))
  await readStream.pipe(writeStream)
  // writeStream.on('close', fn)
  ctx.body = {err:0,msg:'success',data: {img: filePath}}
}
static async getCates(ctx){
    let data = await cateModel.find({}).limit(5)
    ctx.body = { err: 0, msg: 'success', data: {data} }
}

static async getTitle(ctx){
  let { title,page,size } = ctx.request.query
      page= parseInt(page || 1)
      size= parseInt(size || 10)
      const params = {
        title: new RegExp((title||''), 'img')
      }
      console.log(title,'99999999')
      if(!title) delete params.title;
      console.log(params,'0000000')
      const total = await titleModel.find(params)
      const list = await titleModel.find(params).limit(size).skip((page-1)*size)
      ctx.body= {
        err:0,
        msg:'success',
        data:{total,list}
      }
}

static async addTitle(ctx){
  let {name,author,content,digest,image,type }=ctx.request.body
  image =image || ''
  const params={
    title:name,author,digest,type,image,content
  }
  const re=await titleModel.insertMany([params])
  ctx.body = { err: 0, msg: '添加成功' }
}

}

module.exports = TitleController